# coding:utf-8

# main.py 主逻辑 & 程序入口
# Author: Angelic47

import sys
import os
import datetime
import xlwt
import time
import importlib
import client
import globals
from cfghelper import *
from applogger import AppLogger
from luat import LuatModule
execfile("../cfg/at/other.cfg")

cmdtime = {}
succes_test_time = []
failed_test_time = []

logPath = '../out/BasicTest.log'
argv = range(3)
argv[0] = dev_port
argv[1] = os.path.join(os.path.dirname(__file__),
                       "..", "cfg", "at", at_test_cfg)
argv[2] = "../out/" + output_excel
log_all = "../out/logall"
globals.setLogger(AppLogger(True, logPath))
baudrate = "115200"
filename = argv[1]
xlsfilename = argv[2]

# 从配置文件中读取数据, 直接作为python代码执行
execfile(filename)

# 初始化测试环境
luatTest = LuatModule(port=argv[0])
passed = []
failed = []
timedout = []
unknown = []
suceseCmdtime = []
failCmdtime = []
# 开始测试
# 单次测试命令
test_is_ok = True
testResult = ''
now_test_time = 0


for j in range(test_basic_loop):
    globals.getLogger().logline(u"正在测试第 " + str(j)+u"次")
    now_test_time = j
    if test_is_ok:
        for i in cmdlist:
            time1 = time.clock()
            if len(i) > 6:
                err_info = u''' ********************************************************
                测试命令不符合规则:
                1.	修改配置文件格式为[命令类型, '命令字符', '结果', 超时时间, 错误等级]，
                2.	"命令类型" 分为4种，0：AT指令 1：延迟 2：数据 3:嵌套运行另外的cmdlist’
                3.	"错误等级" 分为2种，0忽略错误继续运行，1停止运行
                注意:
                    1,当"命令类型" 为1 的时候 "命令字符" 为延迟时间(单位ms)
                    2,当"命令类型" 为3 的时候,嵌套的里面的命令也要和本格式相同
                本次运行结束
                *********************************************************
                '''
                globals.getLogger().logPrefixln(err_info)
                # globals.getLogger().logPrefixln('INFO',err_info)
                # globals.getLogger().logPrefixln('INFO', 'AT指令已经成功测试了%d条, %d条失败' % (len(passed), len(failed)))
                break
            elif i[0] == 0:
                globals.getLogger().logPrefixln(
                    'INFO', 'Testing %s, timeout: %d' % (repr(i[1]), i[3]))
            elif i[0] == 1:
                globals.getLogger().logPrefixln(
                    'INFO', 'delay time %d' % (i[1]))
            elif i[0] == 2:
                globals.getLogger().logPrefixln('INFO', 'send data')
            elif i[0] == 3:
                suceseCmdtime.append(
                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                succes_test_time.append(time.clock() - time1)
                # globals.getLogger().logPrefixln("test time : ", str(time.clock() -time1))
                passed.append("***Enter embed Test***")
                globals.failed_path.append(i[5])
                globals.getLogger().logPrefixln('INFO', 'Testing embed Cmd')
            time1 = time.clock()
            testResult = luatTest.testCmd(i[0], i[1], i[2], i[3], i[4], passed,
                                          failed, suceseCmdtime, failCmdtime, succes_test_time, failed_test_time)
            cmdtime[i[0]] = datetime.datetime.now().strftime(
                '%Y-%m-%d %H:%M:%S')
            cmdName = "d"
            if(testResult == "OK"):
                if i[0] == 0:
                    cmdName = i[1]
                elif i[0] == 1:
                    cmdName = "***Delay:"+str(i[1])+"ms***"
                elif i[0] == 2:
                    cmdName = "***Send data:" + str(i[1]+"***")
                elif i[0] == 3:
                    globals.failed_path.pop()
                    cmdName = "***Exit embed Test***"
                suceseCmdtime.append(
                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                succes_test_time.append(time.clock() - time1)
                if i[0] == 2 or i[0] == 0:
                    globals.getLogger().logPrefixln("test time : ", str(time.clock() - time1))
                passed.append(repr(cmdName))
            else:
                if testResult == '':
                    testResult = "timeout"
                tempRes = ""
                for Ti in testResult:
                    if ord(Ti) < 32 and ord(Ti) > 126:
                        t = hex(ord(Ti))
                    else:
                        t = Ti
                    tempRes = tempRes+t
                    pass
                globals.getLogger().logPrefixln(
                    'ERROR', 'Command %s failed, error reason: %s' % (i[0], tempRes))
                # failed.append(i[0])
                if i[0] == 0:
                    cmdName = i[1]
                elif i[0] == 1:
                    cmdName = "***Delay:"+str(i[1])+"ms***"
                elif i[0] == 2:
                    cmdName = "***Send data:" + str(i[1]+"***")
                elif i[0] == 3:
                    globals.failed_path.pop()
                    cmdName = "***Exit embed Test***"
                if len(i) > 4 and i[4] == 1 and cmdName != "***Exit embed Test***":
                    failCmdtime.append(
                        datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                    failed_test_time.append(time.clock() - time1)
                    failed.append(
                        repr('/'.join(globals.failed_path)+'/'+cmdName))
                    globals.error_msg.append(repr(tempRes))
                test_is_ok = False
                break
    else:
        break


luatTest.serialport.close()
# 循环测试命令
'''
while len(loopcmdlist):
    for i in loopcmdlist:
        globals.getLogger().logPrefixln('INFO', 'Testing %s, timeout: %d' % (i[0], i[2]))
        testResult = luatTest.testCmd(i[0], i[1], i[2])
        cmdtime[i[0]] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if(testResult == "OK"):
            passed.append(i[0])
        else:
            globals.getLogger().logPrefixln('ERROR', 'Command %s failed test: ERROR found' % (i[0],))
            failed.append(i[0])
            break
    if len(failed) > 0:
        break
'''
# 输出测试结果
if(len(unknown) == 0):
    globals.getLogger().logPrefixln('INFO', u'AT指令已经成功测试了%d条, %d条失败 第 %d 测试' %
                                    (len(passed), len(failed), now_test_time))
else:
    globals.getLogger().logPrefixln('INFO', u'AT指令已经成功测试了%d条, %d条失败 第 %d 测试 ' %
                                    (len(passed), len(failed), now_test_time))

if(len(failed) > 0):
    globals.getLogger().logPrefixln('ERROR', 'Commands failed: ')
    for i in failed:
        globals.getLogger().logPrefixln('ERROR', str(i))

# 导出Excel(xls)
if(xlsfilename != False):
    # 创建workbook
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet('TestResult')
    # 样式
    titleStyle = xlwt.XFStyle()
    titleFont = xlwt.Font()
    titleFont.name = u'微软雅黑'
    titleFont.height = 16 * 20
    titleStyle.font = titleFont
    titleAlignment = xlwt.Alignment()
    titleAlignment.horz = xlwt.Alignment.HORZ_CENTER
    titleStyle.alignment = titleAlignment

    cellPassPattern = xlwt.Pattern()
    cellPassPattern.pattern = xlwt.Pattern.SOLID_PATTERN
    cellPassPattern.pattern_fore_colour = 0x2a
    cellPassStyle = xlwt.XFStyle()
    cellPassStyle.pattern = cellPassPattern

    cellErrorPattern = xlwt.Pattern()
    cellErrorPattern.pattern = xlwt.Pattern.SOLID_PATTERN
    cellErrorPattern.pattern_fore_colour = 0x34
    cellErrorStyle = xlwt.XFStyle()
    cellErrorStyle.pattern = cellErrorPattern

    cellTimeoutPattern = xlwt.Pattern()
    cellTimeoutPattern.pattern = xlwt.Pattern.SOLID_PATTERN
    cellTimeoutPattern.pattern_fore_colour = 0x2b
    cellTimeoutStyle = xlwt.XFStyle()
    cellTimeoutStyle.pattern = cellTimeoutPattern

    cellUnknownPattern = xlwt.Pattern()
    cellUnknownPattern.pattern = xlwt.Pattern.SOLID_PATTERN
    cellUnknownPattern.pattern_fore_colour = 0x0e
    cellUnknownStyle = xlwt.XFStyle()
    cellUnknownStyle.pattern = cellUnknownPattern

    # 开始写入
    sheet.col(0).width = 0x0d00 + 50 * 230
    sheet.col(1).width = 0x0d00 + 50 * 18
    sheet.col(2).width = 0x0d00 + 50 * 23
    sheet.write_merge(0, 0, 0, 2, '测试通过指令'.decode('utf-8'), titleStyle)
    line = 1
    # print "passed:",passed
    for i in range(0, len(passed)):
        sheet.write(line, 0, passed[i], cellPassStyle)
        sheet.write(line, 1, 'PASS', cellPassStyle)
        sheet.write(line, 2, suceseCmdtime[i], cellPassStyle)
        # sheet.write(line, 3, succes_test_time[i], cellErrorStyle)
        # if i in cmdtime:
        ss = open(log_all, "a")
        ss.write("PASS  "+passed[i]+" "+suceseCmdtime[i]+" \r\n")
        ss.close()
        line += 1

    ss = open(log_all, "a")
    ss.write("*************************************\r\n")
    ss.close()
    if(len(failed) > 0 or len(timedout) > 0 or len(unknown) > 0):
        line += 2
        sheet.write_merge(line, line, 0, 2,
                          '测试未通过指令'.decode('utf-8'), titleStyle)
        line += 1
        # print "failed:", failed
        for i in range(0, len(failed)):
            sheet.write(line, 0, failed[i], cellErrorStyle)
            sheet.write(line, 1, testResult, cellErrorStyle)
            sheet.write(line, 2, failCmdtime[i], cellErrorStyle)
            # sheet.write(line,3,failed_test_time[i],cellErrorStyle)
            line += 1
            # if i in cmdtime:
            ss = open(log_all, "a")
            ss.write("Failed  " + failed[i]+" " +
                     str(testResult)+failCmdtime[i] + " \r\n")
            client.at(
                "Failed  " + failed[i]+" "+failCmdtime[i])
            ss.close()
    ss = open(log_all, "a")
    ss.write("*************************************\r\n")
    ss.close()
    wbk.save(xlsfilename)

# sys.exit(0)
